import os
from PIL import Image
from celery_app import app
from models import Task, ImageUpload, db  # 直接从 models 导入
from datetime import datetime

@app.task(bind=True)
def process_image(self, image_id):
    try:
        # 直接通过 ID 查询，不使用关联
        image = ImageUpload.query.get(image_id)
        if not image:
            raise ValueError(f"图片ID {image_id} 不存在")

        # 生成缩略图
        input_path = image.file_path
        output_dir = os.path.dirname(input_path)
        filename = os.path.basename(input_path)
        output_path = os.path.join(output_dir, f"thumbnail_{filename}")

        with Image.open(input_path) as img:
            img.thumbnail((200, 200))
            img.save(output_path)

        # 更新任务（通过 celery_task_id 查询）
        task = Task.query.filter_by(celery_task_id=self.request.id).first()
        if task:
            task.status = "SUCCESS"
            task.result = output_path
            task.completed_at = datetime.utcnow()
            db.session.commit()

        return output_path

    except Exception as e:
        task = Task.query.filter_by(celery_task_id=self.request.id).first()
        if task:
            task.status = "FAILURE"
            task.result = str(e)
            task.completed_at = datetime.utcnow()
            db.session.commit()
        raise